package com.example.utils.initializationconfig;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * @Description
 * @ClassName InitializingBeanExampleBeanTwo
 * @Author jiang_11445266119198
 * @Date 2022/9/11 20:24
 */
@Component
@Slf4j
public class InitializingBeanExampleBeanTwo implements InitializingBean {

    private BlockingQueue<users> queue;

    private boolean isRuning = false;

    private final List<TaskThread> threads = new LinkedList<>();

    @Override
    public void afterPropertiesSet() throws Exception {
        log.info("start Daemon Thread ...");
        queue = new LinkedBlockingQueue<>();
        TaskThread taskThread = new TaskThread();
        // 线程名称
        taskThread.setName("Thread-" + 1);
        // 守护线程
        taskThread.setDaemon(true);
        isRuning = true;
        threads.add(taskThread);
        threads.forEach(Thread::start);
        log.info(String.valueOf(threads.size()));
        log.info("启动成功！");
    }

    public void submitTaskByTaskId(users users){
        boolean offer = this.queue.offer(users);
        log.info("是否写入成功： " + offer);
    }


    private class TaskThread extends Thread{
        @Override
        public void run() {
            while (isRuning){
                try {
                    users take = queue.take();
                    System.out.println("队列数据 = " + take);
                    // 根据业务进行代码书写  可以导入service
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }

        }
    }
}
